package producer

import (
	"errors"
	"gin-vue-admin/global"
	"gin-vue-admin/kafka"
	"gin-vue-admin/model"
	"gin-vue-admin/service"
	"go.uber.org/zap"
)

type parseFunc func(id int) (string, error)

func parseMindScale(id int) (res string, err error) {
	var mindScale model.MindScale
	err = global.GVA_DB.First(&mindScale, id).Error
	mindScale.ReqState = 1
	global.GVA_DB.Save(mindScale)
	res = mindScale.Input
	return
}

func parseFakeDetect(id int) (res string, err error) {
	var fakeDetect model.FakeDetect
	err = global.GVA_DB.First(&fakeDetect, id).Error
	fakeDetect.ReqState = 1
	global.GVA_DB.Save(fakeDetect)
	res = fakeDetect.Input
	return
}

var parseFuncs = map[string]parseFunc{
	// 注册parse方法 key为ReqName(前端的路由名称)
	"mindScale":  parseMindScale,
	"fakeDetect": parseFakeDetect,
}

func SendReq(req *model.ReqMessage) (err error) {
	//  创建 req_msg 记录
	var data string
	if err := service.CreateReqMessage(req); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Any("err", err))
		return err
	}
	// 根据req解析出需要传递的data信息
	if data, err = getData(req); err != nil {
		return err
	}
	//发送 Kafka 主题消息
	asyncProducer.producer(&kafka.Msg{
		ReqMessage: *req,
		Data:       data,
	})
	return
}

func getData(req *model.ReqMessage) (data string, err error) {
	if v, ok := parseFuncs[req.ReqName]; ok {
		return v(req.RequestID)
	} else {
		return "", errors.New("kafka parse func key Not Found")
	}
}
